package cn.com.libertymutual.sp.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaBuilder.In;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.com.libertymutual.core.security.encoder.Md5PwdEncoder;
import cn.com.libertymutual.core.util.Current;
import cn.com.libertymutual.core.web.ServiceResult;
import cn.com.libertymutual.sp.service.api.AdminService;
import cn.com.libertymutual.sys.bean.SysRole;
import cn.com.libertymutual.sys.bean.SysRoleUser;
import cn.com.libertymutual.sys.bean.SysUser;
import cn.com.libertymutual.sys.dao.ISysRoleDao;
import cn.com.libertymutual.sys.dao.ISysRoleUserDao;
import cn.com.libertymutual.sys.dao.ISysUserDao;
import cn.com.libertymutual.sys.service.api.ILdapService;

@Service("adminService")
public class AdminServiceImpl implements AdminService {

	private Logger log = LoggerFactory.getLogger(getClass());
	@Autowired
	private ISysUserDao iSysUserDao;

	@Autowired
	private ISysRoleUserDao iSysRoleUserDao;
	@Autowired
	private NamedParameterJdbcTemplate readJdbcTemplate2;
	@Autowired
	private ISysRoleDao iSysRoleDao;

	@Resource(name = "adServiceImpl") // 需要使用LDAP才使用这个 ldapServiceImpl
	///// private LdapServiceImpl ldapService;
	private ILdapService ldapService;

	@Override
	public ServiceResult adminList(String userid, String username,Integer roleid, int pageNumber, int pageSize) {

		ServiceResult sr = new ServiceResult();
		Sort sort = new Sort(Direction.DESC, "userid");

		Page<SysUser> page = iSysUserDao.findAll(new Specification<SysUser>() {
			@Override
			public Predicate toPredicate(Root<SysUser> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

				List<Predicate> predicate = new ArrayList<Predicate>();
				if (StringUtils.isNotEmpty(username)) {
					if ("flowNode".equals(username)) {
						List<SysUser> users = iSysUserDao.findApproveUser();
						if (CollectionUtils.isNotEmpty(users)) {
							In<String> in = cb.in(root.get("userid").as(String.class));
							for (SysUser ru : users) {
								in.value(ru.getUserid());
							}
							predicate.add(in);
						} 
					}else {
						predicate.add(cb.like(root.get("username").as(String.class), "%" + username + "%"));
					}
				}
				if (StringUtils.isNotEmpty(userid)) {
					predicate.add(cb.like(root.get("userid").as(String.class), "%" + userid+ "%"));
				}
				
				if (null!=roleid) {
					List<SysRoleUser> rus = iSysRoleUserDao.findByRoleid(roleid);
					if (CollectionUtils.isNotEmpty(rus)) {
						In<String> in = cb.in(root.get("userid").as(String.class));
						for (SysRoleUser ru : rus) {
							in.value(ru.getUserid());
						}
						predicate.add(in);
					} else {
						predicate.add(cb.equal(root.get("userid").as(String.class), username));
					}
				}
//				predicate.add(cb.equal(root.get("type").as(String.class), "0"));
				Predicate[] pre = new Predicate[predicate.size()];
				return query.where(predicate.toArray(pre)).getRestriction();
			}
		}, PageRequest.of(pageNumber - 1, pageSize, sort));
		List<SysUser> users = page.getContent();
		for (SysUser user:users) {
			SysRoleUser ru = iSysRoleUserDao.findByUserid(user.getUserid());
			if (null!=ru) {
				user.setRole(iSysRoleDao.findByRoleid(ru.getRoleid()));
			}
		}
		sr.setResult(page);
		return sr;
	}

	
//	@Override
//	public ServiceResult adminList(String userid, String username,Integer roleid, int pageNumber, int pageSize) {
//		ServiceResult sr = new ServiceResult();
//		StringBuilder sql = new StringBuilder();
//		StringBuilder endsql = null;
//		Map<String, Object> paramMap = new HashMap<String, Object>();
//		Integer sqlPageNumber = (pageNumber - 1) * pageSize;
//		sql.append("select u.* from tb_sys_user u ");
//		if (StringUtils.isNotEmpty(userid)||StringUtils.isNotEmpty(username)||null!=roleid) {
//			sql.append(" where ");
//			if (StringUtils.isNotEmpty(userid)) {
//				sql.append(" u.USERID  = :userId and");
//				paramMap.put("userId", userid);
//			}
//			if (StringUtils.isNotEmpty(username)) {
//				sql.append(" u.USERNAME  like :username and");
//				paramMap.put("username", "%"+username+"%");
//			}
//			if (null!=roleid) {
//				sql.append(" left join tb_sys_role_user r on u.USERID = r.USERID and r.ROLEID = :roleid and");
//				paramMap.put("roleid", roleid);
//			}
//			
//			endsql = new StringBuilder(sql.toString().substring(0, sql.toString().length() - 3));
//			log.info("======endsql===={}", endsql.toString());
//
//		} else {
//			endsql = sql;
//		}
//		endsql.append(" limit :sqlPageNumber,:pageSize");
//		paramMap.put("sqlPageNumber", sqlPageNumber);
//		paramMap.put("pageSize", pageSize);
//		log.info("======endsql===={}", endsql.toString());
//		List<Map<String, Object>> list = readJdbcTemplate2.queryForList(endsql.toString(), paramMap);
//		List<SysUser> returnList = Lists.newArrayList();
//		for (int i = 0; i < list.size(); i++) {// 遍历设置实体
//			SysUser user = new SysUser();
//			user.setUserid((String) list.get(i).get("USERID"));
//			user.setUsername((String) list.get(i).get("USERNAME"));
//			user.setUserCode((String) list.get(i).get("USER_CODE"));
//			user.setType((String) list.get(i).get("type"));
//			user.setTermcode((String) list.get(i).get("TERMCODE"));
//			user.setStatus((String) list.get(i).get("STATUS"));
//			user.setSex((String) list.get(i).get("SEX"));
//			user.setRoleCode((String) list.get(i).get("ROLE_CODE"));
//			user.setRemarks((String) list.get(i).get("REMARKS"));
//			user.setPhoneno((String) list.get(i).get("PHONENO"));
//			user.setMobileno((String) list.get(i).get("MOBILENO"));
//			user.setLogoutdate((Date) list.get(i).get("LOGOUTDATE"));
//			user.setLoginnum((Integer) list.get(i).get("LOGINNUM"));
//			user.setLoginip((String) list.get(i).get("LOGINIP"));
//			user.setLastlogindate((Date) list.get(i).get("LASTLOGINDATE"));
//			user.setEmail((String) list.get(i).get("EMAIL"));
//			user.setDisableddate((Date) list.get(i).get("DISABLEDDATE"));
//			user.setDeptcode((String) list.get(i).get("DEPTCODE"));
//			user.setCreater((String) list.get(i).get("CREATER"));
//			user.setCreated((Date) list.get(i).get("CREATED"));
//			user.setClevel((String) list.get(i).get("CLEVEL"));
//			user.setBranchcode((String) list.get(i).get("BRANCHCODE"));
//			user.setAuthtype((String) list.get(i).get("AUTHTYPE"));
//			user.setAuthLevel((String) list.get(i).get("AUTH_LEVEL"));
//			SysRoleUser ru = iSysRoleUserDao.findByUserid(user.getUserid());
//			if (null!=ru) {
//				user.setRole(iSysRoleDao.findByRoleid(ru.getRoleid()));
//			}
//			returnList.add(user);
//		}
//		Map<String, Object> map = new HashMap<String, Object>();
//		Integer i = iSysUserDao.findTotalUser();
//		map.put("list", returnList);
//		map.put("total", i);
//		sr.setResult(map);
//		return sr;
//	}
	
	
	@Override
	public ServiceResult addAdmin(SysUser sysUser) {
		ServiceResult sr = new ServiceResult();
		SysUser dbSysUser = iSysUserDao.findByUserid(sysUser.getUserid());
		if (null != dbSysUser) {
			sr.setAppFail();
			sr.setResult("该用户名已经被使用！");
		} else {
			Md5PwdEncoder md5PwdEncoder = new Md5PwdEncoder();
			sysUser.setLoginnum(0);
			sysUser.setStatus("1");
			sysUser.setPassword(md5PwdEncoder.encodePassword(sysUser.getPassword()));
//			sysUser.setType("0");
			sysUser.setCreated(Current.date.get());
			sysUser.setCreater(Current.userId.get());// add by bob.kuang 20180206 不能通过传入来
			sr.setResult(iSysUserDao.save(sysUser));

		}
		return sr;
	}

	@Override
	public ServiceResult getUserInfoFromLdap(String userId) {

		return ldapService.getUserInfoFromLdap(userId);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED) // 事务
	public ServiceResult setRoleToUser(String userId, Integer roleId) {
		ServiceResult sr = new ServiceResult();
		SysRoleUser dbsru = iSysRoleUserDao.findByUserid(userId);

		if (null != dbsru) {
			dbsru.setRoleid(roleId);
			// sr.setResult(iSysRoleUserDao.save(dbsru));
			iSysRoleUserDao.updateRole(roleId, userId);
			sr.setSuccess();
		} else {
			SysRoleUser sru = new SysRoleUser();
			sru.setRoleid(roleId);
			sru.setUserid(userId);
			sr.setResult(iSysRoleUserDao.save(sru));
		}
		return sr;
	}

	@Override
	public ServiceResult getRoleOfUser(String userId) {

		log.info("----userId---->:" + userId);
		ServiceResult sr = new ServiceResult();
		SysRoleUser dbsr = iSysRoleUserDao.findByUserid(userId);

		if (null != dbsr) {
			sr.setResult(dbsr);
			log.info("----dbsr---->:" + dbsr.toString());
		} else {
			log.info("--------null-------");
			sr.setFail();
		}
		return sr;
	}

	@Override
	public ServiceResult updateAdminStauts(String userid, String type) {
		ServiceResult sr = new ServiceResult();
		// log.info(type);
		// if (type.equals("0")) {
		// SysUser dbSysUser = iSysUserDao.findByUserid(userid);
		// log.info(dbSysUser.toString());
		// dbSysUser.setStatus(type);
		// sr.setResult(iSysUserDao.save(dbSysUser));
		// }else{
		iSysUserDao.updateStatus(type, userid);
		// log.info(dbLossUser.toString());
		// dbLossUser.setStatus(type);
		// sr.setResult(iSysUserDao.save(dbLossUser));
		// }
		sr.setSuccess();
		return sr;
	}
}
